package com.itheima.sh.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;


public class JdbcUtil {
    private static SqlSessionFactory sqlSessionFactory;
    static{
        try {
            String resource = "mybatis-config.xml";
            //加载核心配置文件获取输入流
            InputStream inputStream = Resources.getResourceAsStream(resource);
           sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public static SqlSession getSession(){
        //2.从SqlSessionFactory中获取session
        SqlSession session = sqlSessionFactory.openSession();
        return session;
    }
    public static SqlSession getSession(boolean flag){
        //2.从SqlSessionFactory中获取session
        SqlSession session = sqlSessionFactory.openSession(flag);
        return session;
    }

        public static void commitAndClose(SqlSession session){
            session.commit();
            session.close();
    }

    public static void rollbackAndClose(SqlSession session){
        session.rollback();
        session.close();
    }
}
